function ActivityCtrl($rootScope, $scope,Activity){
    Activity.list({}, function(data){
        $rootScope.activities = data;
    });

    $scope.activity_show = 'all';
    $scope.all_active = 'active';
    $scope.all = function(){
        $scope.activity_show = 'all';
        $scope.all_active = 'active';
        $scope.run_active = '';
        $scope.failed_active = '';
    }
    $scope.running = function(){
        $scope.activity_show = 'running';
        $scope.all_active = '';
        $scope.run_active = 'active';
        $scope.failed_active = '';
    }
    $scope.failed = function(){
        $scope.activity_show = 'failed';
        $scope.all_active = '';
        $scope.run_active = '';
        $scope.failed_active = 'active';
    }

}

/********************************** URL(#/datacenters/:id) Start ********************************/
function DataCenterCtrl($scope, $routeParams, $location, $dialog, DataCenter, Host, VM, Util) {
    $scope.current_target_type = 'DataCenter';
    DataCenter.get({id: $routeParams.id}, function(datacenter){
        $scope.datacenter = datacenter;
        $scope.breadcrumb = Util.breadcrumb(datacenter.name);
        $scope.clusters = $scope.datacenter.cluster_set;

        $scope.hosts_o = Util.flatten($scope.clusters, 'server_set');
        $scope.vms_o = Util.flatten($scope.hosts_o, 'instance_set');
        $scope.storages_o = Util.flatten($scope.clusters, 'storage_set');

        Util.overview($scope);


    });

    $scope.templates = {
        overview: "/static/partials/datacenters/_overview.html",
        events: "/static/partials/datacenters/_events.html",
        hosts: "/static/partials/datacenters/_hosts.html",
        vms: "/static/partials/shared/_vm_list.html",
        networks: "/static/partials/networks/_network_types.html",
        storages: "/static/partials/storages/_storage_list.html",
        backups: "/static/partials/shared/_backups.html",
        tasks: "/static/partials/datacenters/_tasks.html",
        monitors: "/static/partials/monitor/_monitoring.html"
    };
    $scope.current_template = $scope.templates['overview'];

    Util.bind_tab($scope);

    $scope.add_bookmark = function(){
        Util.bookmark($scope,"数据中心", "数据中心快捷方式");
    };
}

function TaskCtrl($scope){
    $scope.current_template = "/static/partials/datacenters/_calendar.html";

    $scope.panechange = function(){
        $scope.current_template = "/static/partials/datacenters/_task_list.html";
    }
    $scope.panechange2 = function(){
        $scope.current_template = "/static/partials/datacenters/_calendar.html";
    }
}

function DataCenterEventCtrl($scope, $routeParams, DataCenterEvent, Util){
    $scope.selected || ($scope.selected = {});
    $scope.page_size = 5;
    $scope.service = function(start, limit){
        DataCenterEvent.get({data_center_id: $routeParams.id, current_page: start, page_size: limit}, function(events, headersFn){
            $scope.events = events.data;
            $scope.total_page = events.total_page;
            $scope.total_count = events.total_count;
        });
    };

    Util.paginate($scope, 'events');

    $scope.do_delete = function(){
        Util.bind($scope, 'events').select(1, 100).confirm("你确定要移除它们吗，此操作将无法恢复!").then(function(events){
            var dataCenterEvent_ids = events.map(function(dataCenterEvent){return dataCenterEvent.id;});
            console.log("REMOVE ALL DataCenterEvent " + dataCenterEvent_ids);
            DataCenterEvent.delete_all({data_center_id: $routeParams.id, ids: dataCenterEvent_ids},
                success = function(data) {
                    $scope.events = data.data;
                    Util.paginate($scope, 'events');
                });
        });
    };

    Util.bind_tab($scope);

    $scope.add_bookmark = function(){
        Util.bookmark($scope, '系统事件', "系统事件快捷方式");
    };
}

/********************************** URL(#/datacenters/:id) End ********************************/


/********************************** URL(#/clusters/:id) Start ********************************/
function ClusterCtrl($scope, $routeParams, Cluster, Host, VM, Util, $location) {
    $scope.current_target_type = 'Cluster';
    Cluster.get({id: $routeParams.id}, function(cluster){
        $scope.cluster = cluster;
        $scope.breadcrumb = Util.breadcrumb(cluster.name);
        $scope.hosts_o = cluster.server_set;
        $scope.vms_o = Util.flatten($scope.hosts_o, 'instance_set');

        $scope.storages_o =cluster.storage_set;

        Util.overview($scope);
    });

    $scope.templates = {
        overview: "/static/partials/clusters/_overview.html",
        hosts: "/static/partials/clusters/_hosts.html",
        vms: "/static/partials/shared/_vm_list.html",
        networks: "/static/partials/networks/_network_types.html",
        backups: "/static/partials/shared/_backups.html",
        storages: "/static/partials/storages/_storage_list.html",
        monitors: "/static/partials/monitor/_monitoring.html",
        disk: "/static/partials/clusters/vdisks.html"
    };
    $scope.current_template = $scope.templates['overview'];

    Util.bind_tab($scope);

    $scope.add_bookmark = function(){
        Util.bookmark($scope, '集群', "集群快捷方式");
    };
}


function MonitoringCtrl($scope, Monitor, Util, $filter){
    console.log($scope.hosts_o);
    angular.forEach($scope.hosts_o,function(host){
        console.log(host.instance_set);
    });
    $scope.monitortemplate = {
        url: "/static/partials/monitor/_monitoring_list.html"
    };
    $scope.targets = [{name:"all",type:"all"},{name: 'CPU', type: 'cpu'}, {name: '内存', type: 'memory'}, {name: '磁盘', type: 'disk'}];
    $scope.timerange = [{name:"一小时内",value:"hour"},{name:"一天内",value:"day"},{name:"一周内",value:"week"},{name:"一月内",value:"month"},{name:"一年内",value:"year"}]
    $scope.intervals = [{name: '1秒', value: '1000'}, {name: '3秒', value: '3000'}, {name: '10秒', value: '10000'}, {name: '30秒', value: '30000'}, {name: '1分', value: '60000'}, {name: '10分', value: '100000'}];
    var today = new Date(), day_hour_ago = new Date();
    day_hour_ago.setTime(today.getTime() - 60 * 60 * 1000);
    $scope.monitoring = {
        start: day_hour_ago.format('yyyy-MM-dd hh:mm:ss'),
        finish: today.format('yyyy-MM-dd hh:mm:ss')
    };
    $scope.monitoring.target = $scope.targets[0];
    $scope.monitoring.interval = $scope.intervals[1];
    $scope.monitoring.timerange = $scope.timerange[0];

    $scope.show_details = function(host, type){
        $scope.monitoring.type = type;
        if(type=='server'){
            $scope.hosttype = "服务器";
            $scope.status_desc = $filter('hoststatus')(host.status);
        }else{
            $scope.hosttype = "虚拟机";
            $scope.status_desc = $filter('vmstatus')(host.status);
        }
        $scope.host = host;
        $scope.monitortemplate.url = "/static/partials/monitor/_monitoring_details.html";
        show_target_image(type);
    };
    $scope.go_back = function(){
        $scope.host = null;
        $scope.monitortemplate.url = "/static/partials/monitor/_monitoring_list.html";
    };

    $scope.show_target_image = show_target_image;
    $scope.show_image = function(image){
        $scope.image_url = image.url;
        Util.dialog("/static/partials/monitor/_monitor_dialog.html", 'showImageCtrl', $scope, {dialogClass: 'modal img-size'});
    }

    $scope.monitor_start_date = $scope.monitoring.start.split(" ")[0]
    $scope.monitor_start_time = $scope.monitoring.start.split(" ")[1]
    $scope.monitor_end_date = $scope.monitoring.finish.split(" ")[0]
    $scope.monitor_end_time = $scope.monitoring.finish.split(" ")[1]

    $scope.show_giventime_image = function(type){
        $scope.monitoring.type = type;
        mstart_date = $("#monitor_start_date").val();
        mstart_time = $("#monitor_start_time").val();
        mend_date = $("#monitor_end_date").val();
        mend_time = $("#monitor_end_time").val();
        if(!mstart_date || !mstart_time || !mend_date || !mend_time){
            return false;
        }
        start_time = mstart_date+" "+mstart_time;
        end_time = mend_date + " " + mend_time;

        if(new Date(Date.parse(start_time))>=new Date(Date.parse(end_time))){
            Util.alert("结束时间必须大于开始时间");
            return false;
        }
        if(new Date(Date.parse(end_time))>new Date()){
            Util.alert("结束时间不能大于当前时间");
            return false;
        }
        if(type=='server'){
            host_name = $scope.host.host_name
        }else if(type=='instance'){
            host_name = $scope.host.name
        }
        target_type = ''
        timerange = ''

        Monitor.do_graph({hostname:host_name,targettype:target_type,starttime:start_time,endtime:end_time,timerange:timerange, type:type}, function(images){
            if(type == 'server'){
                $scope.monitoring.type = 'server'
                $scope.monitoring.cpu_images = images.cpu;
                $scope.monitoring.mem_images = images.memory
                $scope.monitoring.load = images.loads
                $scope.monitoring.disk = images.disk
                $scope.monitoring.interface = images.interface
            }else if(type == 'instance'){
                $scope.monitoring.type = 'instance'
                $scope.monitoring.cpu_images = images.cpu;
                $scope.monitoring.disk = images.disk
                $scope.monitoring.interface = images.interface
            }
//            $('.loading-indicator-modal').modal('hide');
        },function(data){
            if(type=='instance'){
                alert("获取数据失败，请尝试启动虚拟机");
            }else{
                alert("获取数据失败");
            }
        });
    }

    function show_target_image(type){
        if(type=='server'){
            host_name = $scope.host.host_name
        }else if(type=='instance'){
            host_name = $scope.host.name
        }
        target_type = $scope.monitoring.target.type
        start_time = $scope.monitoring.start
        end_time = $scope.monitoring.finish
        timerange = $scope.monitoring.timerange.value
//    	$('.loading-indicator-modal').modal({ backdrop: 'static' });
        Monitor.do_graph({hostname:host_name,targettype:target_type,starttime:start_time,endtime:end_time,timerange:timerange,type:type}, function(images){
            $scope.monitoring.cpu_images = images.cpu;
            $scope.monitoring.mem_images = images.memory
            $scope.monitoring.load = images.loads
            $scope.monitoring.disk = images.disk
            $scope.monitoring.interface = images.interface
//            $('.loading-indicator-modal').modal('hide');
        },function(data){
            if(type=='instance'){
                alert("获取数据失败，请尝试启动虚拟机");
            }else{
                alert("获取数据失败");
            }
        });
    }

    $scope.monitorTime = 0
    $scope.change = function(value){
        if(value==0){
            $("#time_given").attr("style","display:block");
            $("#time_chosen").attr("style","display:none");
        }else{
            $("#time_given").attr("style","display:none");
            $("#time_chosen").attr("style","display:block");
        }
    }
//    $scope.$watch('monitorTime', function(monitorTime) {
//        alert(monitorTime);
//    });

}

/********************************** URL(#/clusters/:id) End ********************************/

/********************************** URL(#/hosts/:id) Start ********************************/
function HostCtrl($scope, $routeParams, Host, VM, Util, $location) {
    $scope.selected || ($scope.selected = {});
    $scope.current_target_type = 'Host';
    Host.get({id: $routeParams.id}, function(host){
        $scope.host = host;
        $scope.breadcrumb = Util.breadcrumb(host.host_name);
        $scope.selected_host = host;
    });

    //主机修改后更新breadcrumb
    $scope.$watch('host.host_name', function (newValue, oldValue) {
        $scope.breadcrumb = Util.breadcrumb(newValue);
    });

    $scope.templates = {
        overview: "/static/partials/hosts/_overview.html",
        vms: "/static/partials/shared/_vm_list.html",
        storages: "/static/partials/storages/_storage_list.html",
        backups: "/static/partials/shared/_backups.html"
    };
    $scope.current_template = $scope.templates['overview'];

    Util.bind_tab($scope);

    $scope.add_bookmark = function(){
        Util.bookmark($scope, '主机', "主机快捷方式");
    };
}

/********************************** URL(#/hosts/:id) End ********************************/

/********************************** URL(#/vms/:id) Start ********************************/
function VMCtrl($scope, $routeParams, VM, Util, $rootScope,$pollingPool,$cookieStore) {
    $scope.selected || ($scope.selected = {});
    VM.get({id:$routeParams.id}, function(vm){
        $scope.vm = vm;
        //为了复用vm list的ctrl
        $scope.selected[vm.id] = vm;
        $scope.vms = [vm];
        $scope.breadcrumb = Util.breadcrumb(vm.name);

        $scope.selected_vm = vm;
        $scope.screen_url = "/api/vm/"+vm.id +"/screen_shot?token="+$cookieStore.get('token');
    });

    $scope.templates = {
        overview: "/static/partials/vms/_overview.html",
        snapshots: "/static/partials/vms/_snapshots.html"
    };
    $scope.current_template = $scope.templates['overview'];

    Util.bind_tab($scope);

    $scope.add_bookmark = function(){
        Util.bookmark($scope, '虚拟机', "虚拟机快捷方式");
    };
    $scope.link_vnc = function(vm){
        open_vnc(vm,$rootScope);
    }

    $pollingPool.add(function(){
        VM.status({ids: $scope.vm.id}, function(data){
            $scope.vm.status = data[0].status;
        },function(e){
            console.log('vm status got :'+ e.data)
        });
        //由于是通过img标签来请求数据，我们无法在头部添加token，所以增加get方式传递token
         $scope.screen_url = "/api/vm/"+$scope.vm.id +"/screen_shot?token="+$cookieStore.get('token');
    },5000)
}

function VMSnapshotCtrl($scope, $routeParams, $location, VM, Util,$pollingPool){
      $scope.page_size = 5;
      $scope.service = function(start, limit){
        VM.snapshot_list({id:$routeParams.id,current_page: start, page_size: limit},function(data){
            $scope.snapshots = data.data;
            $scope.total_page = data.total_page;
            $scope.total_count = data.total_count;
        },function(e){
            console.log(e);
        })
      };

    Util.paginate($scope, 'snapshots');

    $scope.select = function(){
        $scope.snap = this.snapshot;
    }
    $scope.do_add = function(){
        $scope.from_list = true;
        Util.dialog("/static/partials/vms/snapshot_dialog.html", 'SnapshotDialogCtrl', $scope, {backdropClick: false, dialogClass: 'modal mini'});
    }

    $scope.do_recover = function(){
      Util.confirm("当前数据会直接丢弃掉,确定要恢复快照?",function(){
          VM.snapshot_restore({id:$routeParams.id,snap_id:$scope.snap.id},function(data){
                console.log(data);
            })
        });

    }
    $scope.do_delete = function(){
        Util.confirm("当前数据会直接丢弃掉,确定要恢复快照?",function(){
          VM.snapshot_delete({id:$routeParams.id,snap_id:$scope.snap.id},function(data){
                      $pollingPool.add_activity_callback(data.activity,function(){
                          $scope.snap.deleted = true;
                      })

            })
        });
    }


}
/********************************** URL(#/vms/:id) End ********************************/


/********************************** Shared Controller Start ********************************/

function BackupCtrl($scope, $routeParams, Backup, BackupStrategy, Util) {
    var params = {target_id: $routeParams.id, target_type: $scope.current_target_type};
    BackupStrategy.query(params, function(data){
        $scope.backup_strategies = data;
    });

    Backup.status(params, function(data){
        $scope.backup_status = data;
    });

    Backup.list({},function(data){
        $scope.backups = data;
    });
//    Backup.query(params, function(data){
//        $scope.backups = data;
//    });

    $scope.do_reset = function(backup){
        VM.reset_backup({id: backup.instance.id, backup_id: backup.id}, Util.update_activities);
    };
}

function NetworkMgmtCtrl($scope, $dialog, $routeParams, DataCenter,Cluster ,Network, Util,$pollingPool){
//    var params = {target_id: $routeParams.id, target_type: $scope.current_target_type};
    var resource = $scope.current_target_type == 'DataCenter'?DataCenter:Cluster;

    $scope.selected || ($scope.selected = {});
    $scope.page_size = 5;
    $scope.service = function(start, limit){
        resource.networks({id: $routeParams.id, current_page: start, page_size: limit}, function(networks){
            $scope.networks = networks.data;
            $scope.total_page = networks.total_page;
            $scope.total_count = networks.total_count;
        });
    }

    Util.paginate($scope, 'networks');

    $scope.do_delete = function(){
        if($scope.selected_network){
            Util.confirm("你确定要移除网络["+$scope.selected_network.name+"]吗，此操作将无法恢复!",function(){
                Network.delete({id:$scope.selected_network.id},function(data){
                    $pollingPool.add_activity_callback(data.activity,function(){
//                            var index = $scope.networks.indexOf($scope.selected_network);
//                            $scope.networks.splice(index, 1);
                        $scope.selected_network.deleted = true;
                    })
                })
            });

        }else{
            Util.alert('请选择一个网络!');
        }

    };

    $scope.show_details = function(){
        $scope.selected_network = this.network;
    }

    $scope.do_add = function(){
        $scope.update = false;
        $scope.save_method = 'create';
//        $scope.selected_network = {};//不能置空，会导致action bar行为变化
        Util.dialog("/static/partials/networks/_network_dialog.html", 'NetworkConfigDialogCtrl', $scope);
    };

    $scope.do_edit = function(){
        Util.confirm("修改网络将导致关联的虚拟机ip重新分配，您确定要修改吗？",function(){
            $scope.save_method = 'update';
        $scope.update = true;
        Util.dialog("/static/partials/networks/_network_dialog.html", 'NetworkConfigDialogCtrl', $scope);
        })

    };

    $scope.do_fixedip = function() {
        Util.dialog("/static/partials/networks/_network_fixedip.html", 'FixedipDialogCtrl', $scope);
    }

    $scope.show_fixedip = function() {
        return $scope.selected_network&&($scope.selected_network.networktype == 2 || $scope.selected_network.networktype == 3)
                &&$scope.selected_network.rundhcp;
    }
}

function StorageCtrl($scope, $dialog, $routeParams, DataCenter, Cluster,Storage, Util,$pollingPool){
//    var params = {target_id: $routeParams.id, target_type: $scope.current_target_type};
    var resource = $scope.current_target_type == 'DataCenter'?DataCenter:Cluster;
    $scope.selected || ($scope.selected = {});
    $scope.build_storage_path = function(item){
        if(item.protocol=='local')
            item.storage_path = 'local';
        if(item.protocol=='nfs')
            item.storage_path = item.host+":"+item.path;
        if(item.protocol=='iscsi')
            item.storage_path = item.host;
        if(item.protocol=='cifs')
            item.storage_path = item.path;
    }
    $scope.page_size = 5;
    $scope.service = function(start, limit){
        resource.storages({id: $routeParams.id, current_page: start, page_size: limit}, function(storages){
            $scope.storages = storages.data;
            angular.forEach($scope.storages,function(item){
                $scope.build_storage_path(item);
            });
            $scope.total_count = storages.total_count;
            $scope.total_page = storages.total_page;
        });
    }
    Util.paginate($scope, 'storages');

    $scope.show_details = function(){
        $scope.selected_storage = this.storage;
        Storage.status({id:this.storage.id},function(data){
            $scope.extras = data;
        });

    }

    $scope.do_delete = function(){
        Util.confirm("你确定要删除存储["+$scope.selected_storage.name+"]",function(){
            Storage.delete({id:$scope.selected_storage.id},function(data){
                $pollingPool.add_activity_callback(data.activity,function(s){
                    var index = $scope.storages.indexOf($scope.selected_storage);
                    $scope.storages.splice(index, 1);
                });

            },function(s){
                Util.alert(s.data);
            });
        })

    }

    $scope.do_add = function(){
        $scope.selected_storage = null;
        Util.dialog("/static/partials/storages/_storage_dialog.html", 'StorageConfigDialogCtrl', $scope, {dialogClass: 'modal mini'});
    };

    $scope.do_edit = function(){
        Util.bind($scope, 'storages').select(1, 1).then(function(storages){
            $scope.selected_storage = storages[0];
            Util.dialog("/static/partials/storages/_storage_dialog.html", 'StorageConfigDialogCtrl', $scope, {dialogClass: 'modal mini'});
        });
    };
}

/********************************** Shared Controller END ********************************/

/******************************************************** ROOT Section Start *******************************************/
function ShortcutCtrl($scope, $rootScope, Shortcut, Util){
    $scope.selected || ($scope.selected = {});

    $scope.page_size = 5;
    $scope.service = function(start, limit){
        Shortcut.list({current_page: start, page_size: limit}, function(shortcuts){
            $scope.shortcuts = shortcuts.data;
            $scope.total_count = shortcuts.total_count;
            $scope.total_page = shortcuts.total_page;
        });
    };

    Util.paginate($scope, 'shortcuts');

    $scope.do_delete = function(){

        Util.bind($scope, 'shortcuts').select(1, 100).confirm('你确定要移除它们吗，此操作将无法恢复!').then(function(shortcuts){
            var shortcut_ids = shortcuts.map(function(shortcut){return shortcut.id;});

            //console.log("REMOVE ALL storages " + shortcut_ids);
            Shortcut.delete_all({ids: shortcut_ids},
                success = function(data) {
                    $scope.shortcuts = data.data;
//                    Util.paginate($scope, 'shortcuts');
                });

        });
    };

    Util.bind_tab($scope);
}


function TemplateCtrl($scope, $routeParams, Template, Util){

    $scope.selected || ($scope.selected = {});
    $scope.page_size = 5;
    $scope.service = function(start, limit){
        Template.list({current_page: start, page_size: limit, os_type: $scope.os_type}, function(templates){
            $scope.templates = templates.data;
            $scope.total_count = templates.total_count;
            $scope.total_page = templates.total_page;
        });
    };

    Util.paginate($scope, 'templates');

//    $scope.search = function(os_type) {
//
//        $scope.os_type = os_type;
//        Util.paginate($scope, 'templates');
//
//    };

    $scope.do_delete = function(){
        Util.bind($scope, 'templates').select(1, 100).confirm("你确定要移除它们吗，此操作将无法恢复!").then(function(templates){
            var template_ids = templates.map(function(template){return template.id;});

            Template.delete_all({ids: template_ids},
                success = function(data) {
                    angular.forEach($scope.templates,function(item){
                        if(template_ids.indexOf(item.id)!=-1){
                            item.deleted = true;
                        }
                    })
            });
        });
    };

    Util.bind_tab($scope);

    $scope.add_bookmark = function(){
        Util.bookmark($scope, '模板', "模板快捷方式");
    };
}



function NetworkCtrl($scope, $routeParams, Network, Util){

    Util.bind_tab($scope);

    $scope.add_bookmark = function(){
        Util.bookmark($scope, '网络安全', "网络安全快捷方式");
    };
}


function SecurityCtrl($scope) {

    $scope.$on("GroupChange", function(event, security_group_id) {

        $scope.$broadcast("GroupChangeFromParent", security_group_id);
    });
}

function SecurityGroupCtrl($rootScope, $scope, SecurityGroup, Util, SecurityRule) {
    $scope.selected || ($scope.selected = {});
    $scope.page_size = 5;
    $scope.service = function(start, limit){
        SecurityGroup.list({current_page: start, page_size: limit}, function(security_groups){

            $scope.security_groups = security_groups.data;
            $scope.total_count = security_groups.total_count;
            $scope.total_page = security_groups.total_page;
        });
    };
    Util.paginate($scope, 'security_groups');

    $scope.do_delete = function(){
        Util.bind($scope, 'security_groups').select(1, 100).confirm('你确定要移除它们吗，安全组下的安全规则也将会一并删除，此操作将无法恢复!并且关联的虚拟机也会去除规则！').then(function(security_groups){
            var security_group_ids = security_groups.map(function(security_group){return security_group.id;});
            console.log("REMOVE ALL security_rules " + security_group_ids);
            SecurityGroup.delete_all({ids: security_group_ids},
                success = function(data) {
                    angular.forEach($scope.security_groups,function(item){
                        if(security_group_ids.indexOf(item.id)!=-1){
                            item.deleted = true;//use filter activeitem
                        }
                    })
                    $scope.$emit("GroupChange", 0);//清楚规则表格
                }
            );
        });
    };

    $scope.do_add = function(){
        $scope.selected_group = null;
        $scope.update = false;
        Util.dialog("/static/partials/networks/_security_group_dialog.html", "SecurityGroupDialogCtrl", $scope);
    };

    $scope.do_edit = function(){
        Util.bind($scope, 'security_groups').select(1, 1).then(function(security_groups){
            $scope.selected_group = security_groups[0]
            $scope.update = true;
            Util.dialog("/static/partials/networks/_security_group_dialog.html", "SecurityGroupDialogCtrl", $scope);
        });
    };

    $scope.bodyclick = function(security_group) {

        $scope.$emit("GroupChange", security_group.id);
    }

    $scope.related_vm = function(security_group){
        $scope.port_id = security_group.id;
        Util.dialog("/static/partials/networks/_vm_list.html", "RelatedDialogCtrl", $scope);
    }

    Util.bind_tab($scope);
}


function SecurityRuleCtrl($scope, $dialog, $routeParams, SecurityRule, Util){
    $scope.selected || ($scope.selected = {});
    $scope.page_size = 5;
    $scope.service = function(start, limit){
        SecurityRule.list({current_page: start, page_size: limit, group:$scope.group_id}, function(security_rules){

            $scope.security_rules = security_rules.data;
            $scope.total_count = security_rules.total_count;
            $scope.total_page = security_rules.total_page;
        });
    };
    Util.paginate($scope, 'security_rules');

    $scope.do_delete = function(){
        Util.bind($scope, 'security_rules').select(1, 100).confirm('你确定要移除它们吗，此操作将无法恢复!').then(function(security_rules){
            var security_rule_ids = security_rules.map(function(security_rule){return security_rule.id;});
            console.log("REMOVE ALL security_rules " + security_rule_ids);
            SecurityRule.delete_all({ids: security_rule_ids},
                success = function(data) {
                    $scope.security_rules = data.data;
//                    Util.paginate($scope, 'security_rules');
                }
            );
        });
    };

    $scope.do_add = function(){
        $scope.selected_rule = null;
        Util.dialog("/static/partials/networks/_security_rule_dialog.html", "SecurityRuleDialogCtrl", $scope);
    };

    $scope.do_edit = function(){
        Util.bind($scope, 'security_rules').select(1, 1).then(function(security_rules){
            $scope.selected_rule = security_rules[0]
            Util.dialog("/static/partials/networks/_security_rule_dialog.html", "SecurityRuleDialogCtrl", $scope);
        });
    };

    Util.bind_tab($scope);

    $scope.group_id = null;
    $scope.$on("GroupChangeFromParent", function(event, security_group_id) {

        $scope.group_id = security_group_id;
        Util.paginate($scope, 'security_rules');
    });
}


function BackupStrategyCtrl($scope, $dialog, $routeParams, BackupStrategy, Util) {

    $scope.selected || ($scope.selected = {});
    $scope.page_size = 5;
    $scope.service = function(start, limit){
        BackupStrategy.list({current_page: start, page_size: limit}, function(strategies){
            $scope.strategies = strategies.data;
            $scope.total_count = strategies.total_count;
            $scope.total_page = strategies.total_page;
        });
    };

    Util.paginate($scope, 'strategies');

    $scope.do_delete = function(){
        Util.bind($scope, 'strategies').select(1, 100).confirm('你确定要移除它们吗，此操作将无法恢复!').then(function(backupstrategies){
            var backupstrategy_ids = backupstrategies.map(function(backupstrategy){return backupstrategy.id;});

            console.log("REMOVE ALL backupstrategies " + backupstrategy_ids);
            BackupStrategy.delete_all({ids: backupstrategy_ids},
                success = function(data) {
                    $scope.strategies = data.data;
                    Util.paginate($scope, 'strategies');
            });
        });
    }

    $scope.do_add = function(){
        $scope.selected_backupstrategy = null;
        Util.dialog("/static/partials/backupstrategies/_backupstrategy_dialog.html", "BackupStrategyDialogCtrl", $scope, {height:10000});
    };

    $scope.do_edit = function(){

        Util.bind($scope, 'strategies').select(1, 1).then(function(backupstrategies){

            $scope.selected_backupstrategy = backupstrategies[0];
            Util.dialog("/static/partials/backupstrategies/_backupstrategy_dialog.html", "BackupStrategyDialogCtrl", $scope);
        });
    };

    Util.bind_tab($scope);

    $scope.add_bookmark = function(){
        Util.bookmark($scope, '备份策略', "备份策略快捷方式");
    };
}

//function ProposalCtrl($scope, $routeParams, Proposal, Util){
//
//    Util.bind_tab($scope);
//
//    $scope.add_bookmark = function(){
//        Util.bookmark($scope, '方案管理', "方案管理快捷方式");
//    };
//}

function ComputeProposalCtrl($scope, $dialog, $routeParams, Proposal, Util){
    $scope.selected || ($scope.selected = {});


    $scope.page_size = 5;
    Proposal.get(function(proposals){
        $scope.computes = proposals.data;
        Util.paginate($scope, 'computes');
    });

//    $scope.$watch("computes",function(newvalue){
//       $scope.change($scope.page_size);
//    });

    $scope.service = function(start, limit){
        Proposal.list({current_page: start, page_size: limit}, function(proposals){
            $scope.computes = proposals.data;
            $scope.total_count = proposals.total_count;
            $scope.total_page = proposals.total_page;
        });
    }

    $scope.do_delete = function(){
        Util.bind($scope, 'computes').select(1, 100).confirm('你确定要移除它们吗，此操作将无法恢复!').then(function(computes){
            var compute_ids = computes.map(function(compute){return compute.id;});
            console.log("REMOVE ALL storages " + compute_ids);
            Proposal.delete({ids:compute_ids},function(data){
                angular.forEach($scope.computes,function(c,index){
                    if(compute_ids.indexOf(c.id)!=-1){
                        $scope.computes.splice(index,1);

                    }
                });
                $scope.change($scope.page_size);

            });
        });
    }

    $scope.do_edit = function(){
        Util.bind($scope, 'computes').select(1, 1).then(function(computes){
            $scope.selected_compute = computes[0];
            Util.dialog("/static/partials/proposals/_compute_dialog.html", "ComputeProposalDialogCtrl", $scope);
        });
    };
}


function ArchitectCtrl($scope, Util){
    $scope.add_bookmark = function(){
        Util.bookmark($scope, '基础架构', "基础架构快捷方式");
    };
}

function GlobalConfigCtrl($scope, Util, GlobalConfig){

    $scope.hideinfo = false;
    GlobalConfig.get({},function(data){
        $scope.settings = data
    });

    Util.bind_tab($scope);

    $scope.add_bookmark = function(){
        Util.bookmark($scope, '全局配置', "全局配置快捷方式");
    };

    $scope.do_edit = function(){
        $scope.hideinfo = true;
    }

    $scope.close = function(){
        $scope.hideinfo = false;
    }


    $scope.do_update = function(){
        GlobalConfig.update($scope.settings,function(data){
            $scope.settings = data;
        });
        $scope.hideinfo = false;
    }
}

function PlatformCtrl($scope, Util, Platform){
    Util.bind_tab($scope);

    $scope.add_bookmark = function(){
        Util.bookmark($scope, '平台信息', "平台信息快捷方式");
    };

    Platform.info({},function(data){
        $scope.name = data.name;
        $scope.validity = data.validity;
        $scope.total = data.total;
        $scope.available = data.available;
        $scope.version = data.version;
        $scope.hardwareid = data.hardwareid;
        $scope.build = data.build;
    });

    $scope.licenseinfo = ""
    $scope.update_license = function(){
        Util.dialog('/static/partials/platform/license.html', 'PlatformDialogCtrl', $scope);
    }

    $scope.register_license = function(){
        Platform.register_license({"licenseinfo":$scope.licenseinfo},function(data){
            if(data.status==200){
                Util.alert("认证更新成功");
                window.location.href="/web/index.html"
            }else{
                Util.alert(data.msg);
                dialog.close()
            }
        });
    }
}
/******************************************************** ROOT Section End *******************************************/
function GuideController($scope,$location, Util,DataCenter){
    DataCenter.list({},function(data){
        if(data.length!=0){
            $location.path('/datacenter/'+data[0].id);
        }else{
            Util.dialog('/static/partials/guides/index.html', 'GuideDialogCtrl', $scope, {backdropClick: false,keyboard:false});
        }
    });
//
//    $scope.isInit = false;
//    if($scope.isInit){
//        $location.path( "/datacenters/1");
//    }else{
//        Util.dialog('/static/partials/guides/index.html', 'GuideDialogCtrl', $scope, {backdropClick: false,keyboard:false});
//    }
}


function UserCtrl($scope,User,Util,$cookieStore,$http,$pollingPool){
    $scope.selected || ($scope.selected = {});
    $scope.page_size = 5;
    $scope.service = function(start, limit){
        User.list({current_page: start, page_size: limit}, function(users){
            $scope.users = users.data;
            $scope.total_count = users.total_count;
            $scope.total_page = users.total_page;
        });
    };

    Util.paginate($scope, 'users');

    $scope.select = function(){
        $scope.selected_user = this.user;
    }

    $scope.token = $cookieStore.get('token');

    $scope.do_add = function(){
        $scope.title = "添加用户";
        $scope.method = 'create';
        Util.dialog('/static/partials/user/_user_dialog.html', 'userDialogCtrl', $scope, {backdropClick: false,keyboard:false,dialogClass: 'modal mini'});
    }

    $scope.do_edit = function(){
        $scope.title = "修改用户";
        $scope.method = 'update';
        Util.dialog('/static/partials/user/_user_dialog.html', 'userDialogCtrl', $scope, {backdropClick: false,keyboard:false,dialogClass: 'modal mini'});
    }

    $scope.do_delete = function(){
      Util.bind($scope, 'users').select(1, 100).confirm('确定要删除用户吗？').then(function(users){
          var userids = users.map(function(user){ return user.id; });
          User.delete({ids:userids},function(data){
              users.map(function(user){user.deleted=true;});
          })
        });
    }

    $scope.do_open = function(){
        Util.bind($scope, 'users').select(1, 100).confirm('确定要激活用户吗？').then(function(users){
          var userids = users.map(function(user){ return user.id; });
          User.active({ids:userids},function(data){
              users.map(function(user){user.status='offline';});
          })
        });
    }

    $scope.do_close = function(){
        Util.bind($scope, 'users').select(1, 100).confirm('确定要禁用用户吗？').then(function(users){
          var shouldnotice = false;
          var userids = users.map(function(user){
              if(user.status == 'online'){
                  shouldnotice = true;
              }else{
                  return user.id;
              }
          });

          userids = $.grep(userids,function(u){return u;})

          if(shouldnotice) Util.alert('提示：已经在线的用户将被忽略掉!');

          User.deny({ids:userids},function(data){
              users.map(function(user){if(user.status!='online') user.status='deny';});
          })
        });
    }

    $scope.onFileSelect = function($files) {
          var $file = $files[0];
          $http.uploadFile({
            url: '/api/users/import_users',
            file: $file
          }).success(function(data, status, headers, config) {
                angular.forEach(data,function(user){
                  $scope.users.push(user);
                })
                Util.alert('导入成功，本次新增'+data.length+'个用户');
                ngfile.value = '';  //清空上次的选择，因为file input是出发change事件的
          }).error(function(data){
                Util.alert(Util.decode_error_msg(data));
                ngfile.value = '';
          });
      }

    var ngfile = angular.element.find('input[ng-file-select]')[0];
    $scope.do_import = function(){
        ngfile.click();
    }

    $scope.do_attach_vm = function(){
        Util.dialog("/static/partials/user/attach_vm.html", "attach_vm_ctrl", $scope, {backdropClick: false, dialogClass: 'modal mini'});
    }

    $pollingPool.add(function(){
        User.list({current_page: $scope.current_page + 1, page_size: $scope.page_size}, function(data){
            angular.forEach(data.data,function(item){
                angular.forEach($scope.users,function(user){
                    if(item.id == user.id){
                        user.status = item.status;
                    }
                })
            })
        });
    },2000)
}
